package pt.ipleiria.plp.ui;

import de.enough.polish.ui.Alert;
import de.enough.polish.ui.AlertType;
import de.enough.polish.ui.Command;
import de.enough.polish.ui.CommandListener;
import de.enough.polish.ui.Displayable;
import de.enough.polish.ui.List;
import de.enough.polish.util.Locale;
import java.io.IOException;
import java.util.Enumeration;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import pt.ipleiria.plp.ImagePath;
import pt.ipleiria.plp.Utils;
import pt.ipleiria.plp.threads.GetFilesInPhotoDir;

/**
 *
 * @author Filipe
 */
public class PhotoBrowser extends List implements CommandListener {

    private String path;
    private Command cmdOK = new Command(Locale.get("cmd.OK"), Command.CANCEL, 1);
    private Command cmdCanc = new Command(Locale.get("cmd.Cancelar"), Command.EXIT, 2);
    private EventoScreen screen;

    public PhotoBrowser(EventoScreen screen) {
        //#style defaultScreen
        super(Locale.get("title.ImBrow"), List.MULTIPLE);
        this.screen = screen;

        GetFilesInPhotoDir t = new GetFilesInPhotoDir(this);

        t.start();
    }

    public void returnFilesInDir(Enumeration files, String path) {

        if (files == null) {
            Alert alert = new Alert(Locale.get("title.direcVazio"),
                        Locale.get("mensagens.direcVazio"), null, AlertType.INFO);
            screen.getMidlet().getDisplay().setCurrent(alert, screen);
        }

        while (files.hasMoreElements()) {
            //#style multipleChoice
            this.append(((String) files.nextElement()), null);
        }
        if (this.size() == 0) {
            Alert alert = new Alert(Locale.get("title.direcVazio"),
                        Locale.get("mensagens.direcVazio"), null, AlertType.INFO);
            screen.getMidlet().getDisplay().setCurrent(alert, screen);
        }

        this.path = path;
        this.setCommandListener(this);
        this.addCommand(cmdOK);
        this.addCommand(cmdCanc);

    }

    public void commandAction(Command c, Displayable d) {

        if (c == cmdOK) {
            String strings[] = Utils.getSelectedStrings(this);
            //DEBUG
            for(int i = 0 ; i< this.size(); i++){
                System.out.println("list item "+i+": "+this.isSelected(i));
            }
            //DEBUG
            if (strings.length > 0) {

                ImagePath[] images = new ImagePath[strings.length];

                for (int i = 0; i < strings.length; i++) {

                    //O image type esta hardcoded por falta de tempo deveria
                    //ser um concreto
                    System.out.println("IMAGEM: "+path+strings[i]);
                    images[i] = new ImagePath(path+strings[i],strings[i], "", "image/jpeg");
                }
                screen.returnFromPhoto(images);
            }

        } else if (c == cmdCanc) {
            screen.returnFromPhoto(null);
        }

    }

}
